package org.ooda.distributedsys.loginmodule.interceptors;

import org.ooda.distributedsys.loginmodule.common.ResponseHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: distributedSys
 * @description: login interceptor implement
 * @author: Aprilies
 * @create: 2023-03-18 09:26
 **/

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equals("OPTIONS")){
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        String authorization = request.getHeader("Authorization");
        // authorization is empty
        if (authorization == null) {
            ResponseEntity<Object> responseEntity = ResponseHandler.generateResponse("token is empty", HttpStatus.UNAUTHORIZED, null);
            // get ResponseEntity json form
            String s = new ObjectMapper().writeValueAsString(responseEntity.getBody());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(s);
            response.flushBuffer();
            return false;
        }
        try{
            Jws<Claims> jws = Jwts.parser()
                    .setSigningKey("mysecretkey")
                    .parseClaimsJws(authorization);
        } catch (Exception e){
            ResponseEntity<Object> responseEntity = ResponseHandler.generateResponse("tokoen is invalid", HttpStatus.UNAUTHORIZED, null);
            String s = new ObjectMapper().writeValueAsString(responseEntity.getBody());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(s);
            response.flushBuffer();
            return false;
        }
        return true;
    }
}
